//
//  NSString+Common.m
//  GFrameWork
//
//  Created by qiang on 14-8-21.
//  Copyright (c) 2014年 Gable. All rights reserved.
//

#import "NSString+Common.h"
#import "CommonCrypto/CommonDigest.h"



@implementation NSString (Common)
+(NSString *)MD5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
    
}
+(BOOL) isEmpty:(NSString *) str {
    
    if ([str isKindOfClass:[NSNull class]])
    {
        return true;
    }
    if (!str)
    {
        return true;
    } else {
        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

//计算高度
+(CGFloat)calculateTextHeight:(CGFloat)widthInput Content:(NSString *)strContent  font:(UIFont *)font
{
    CGSize constraint = CGSizeMake(widthInput, 20000.0f);
    CGSize size = [strContent sizeWithFont:font constrainedToSize:constraint];
    CGFloat height = ceilf(size.height);
    return height;
}

//计算 宽度
+(CGFloat)calculateTextWidth:(CGFloat)widthInput Content:(NSString *)strContent  font:(UIFont *)font
{
//    if(iOS7) {
//        CGSize size = CGSizeMake(20000.0f, widthInput);
//        NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
//        return [strContent boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:tdic context:nil].size.width;
//    } else {
    
        CGFloat constrainedSize = 150.0f; //其他大小也行
        CGSize size = [strContent sizeWithFont:font constrainedToSize:CGSizeMake(constrainedSize, 30)];
//        CGFloat width = MIN(size.width, 100.0f);
        return size.width;
//    }
}

+(BOOL)isMobileNumber:(NSString *)mobileNum
{
    /*
     MOBILE = @"^[\u4e00-\u9fa5]{2,6}$"; //判断2~10位中文 姓名
      MOBILE = @"^[\\d]{15}||[\\d]{18}||[\\d]{14}[x||X]{1}||[\\d]{17}[x||X]{1}$";//15 或18位身份证 包括最后一位为x/X
     */
    NSString * MOBILE = @"^1\\d{10}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES)
        
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
+(BOOL)isValidateEmail:(NSString *)msg {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:msg];
}

+(BOOL)istecentqq:(NSString *)qqnum
{
    NSString *qq = @"[1-9](\\d){3,11}";
    NSPredicate *testqq = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",qq];
    if ([testqq evaluateWithObject:qqnum] == YES) {
        return  YES;
    }
    else
    {
        return NO;
    }
}
+(BOOL)isContainsTelStr:(NSString *)Str//字符串中是否包含联系方式
{
    NSString *url = Str;
    NSError *error;
    // 创建NSRegularExpression对象并指定正则表达式
    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:@"[1-9](\\d){3,11}"
                                  options:0
                                  error:&error];
    if (!error) { // 如果没有错误
        // 获取特特定字符串的范围
        NSTextCheckingResult *match = [regex firstMatchInString:url
                                                        options:0
                                                          range:NSMakeRange(0, [url length])];
        if (match) {
            // 截获特定的字符串
            NSString *result = [url substringWithRange:match.range];
            CDLog(@"%@",result);
            return YES;
        }
    } else { // 如果有错误，则把错误打印出来
        CDLog(@"error - %@", error);
        return NO;
    }
    
    return NO;
}
+(BOOL)testinputmoney:(UITextField *)textField andrange:(NSRange)range andString:(NSString *)string
{
    
    NSString *tobestring = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([tobestring isEqualToString:@"."]) {
        textField.text = @"0.";
        return NO;
    }
    if ([textField.text isEqualToString:@"0"]) {
        if ([string isEqualToString:@"0"]) {
            return NO;
        }
        else if ([string isEqualToString:@"."]) {
            return YES;
        }
        else
        {
            textField.text = string;
            return NO;
        }
    }
    
    NSString * numAndDot = @"^\\d{0,10}\\.?\\d{0,2}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numAndDot];
    if ([regextestmobile evaluateWithObject:tobestring] == YES)
        
    {
        return YES;
    }
    else
    {
        return NO;
    }
    
}
+(NSString *)returnStrFromarray:(NSMutableArray *)arrStrs
{
    NSString *tempstr = @"            ";
    NSString *returnstr=@"";
    NSString *mystr;
    for (int i =0; i<arrStrs.count; i++) {
        mystr = [[arrStrs objectAtIndex:i] stringByAppendingString:tempstr];
        returnstr = [returnstr stringByAppendingString:mystr];
    }
    
    return returnstr;
}

+(BOOL)ispasswd:(NSString *)passwdStr
{
    NSString * MOBILE = @"\\w{6,20}";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:passwdStr] == YES)
        
    {
        return YES;
    }
    else
    {
        return NO;
    }
    
}

//+(BOOL)lzqstringtest:(NSString *)str andtag:(int)tag
//{
//    NSString * MOBILE;
//    if (tag == KchineseNameTag) {
//        MOBILE = @"^[\u4e00-\u9fa5]{2,6}$"; //判断2~10位中文 姓名
//    }
//    else if (tag == KchineseIdCardTag){
//        MOBILE = @"^[\\d]{15}||[\\d]{18}||[\\d]{14}[x||X]{1}||[\\d]{17}[x||X]{1}$";//15 或18位身份证 包括最后一位为x/X
//    }
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    if ([regextestmobile evaluateWithObject:str] == YES)
//        
//    {
//        return YES;
//    }
//    else
//    {
//        return NO;
//    }
//    
//}


//+(NSString *)cookieValueWithKey:(NSString *)key
//{
//    NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    
//    if ([sharedHTTPCookieStorage cookieAcceptPolicy] != NSHTTPCookieAcceptPolicyAlways) {
//        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
//    }
//    
//    NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:SERVICE_URL]];
//    NSEnumerator    *enumerator = [cookies objectEnumerator];
//    NSHTTPCookie    *cookie;
//    while (cookie = [enumerator nextObject]) {
//        if ([[cookie name] isEqualToString:key]) {
//            return [NSString stringWithString:[[cookie value] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//        }
//    }
//    
//    return nil;
//}

+(NSMutableAttributedString *)getAttributedStrFromStr:(NSString *)content andFont:(UIFont *)font andTextColor:(UIColor *)color andRange:(NSRange)range
{
    NSMutableAttributedString *myattributedString = [[NSMutableAttributedString alloc] initWithString:content];
    
    [myattributedString setAttributes:@{NSForegroundColorAttributeName:color, NSFontAttributeName : font} range:range];
    return myattributedString;
}

+(NSString *)sortRequestData:(NSDictionary *)dic
{
    if (dic == nil) {
        return nil;
    }
    else
    {
        NSString *requestStr = @"";
        NSArray *keys = [dic allKeys];
        if (keys.count==0) {
            return nil;
        }
        NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            return [obj1 compare:obj2 options:NSNumericSearch];
        }];
        for (NSString *categoryId in sortedArray) {
            
            requestStr = [requestStr stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",categoryId,[dic objectForKey:categoryId]]];
        }
        
        CDLog(@"处理前requstStr=%@",requestStr);
        NSInteger leng = requestStr.length;
        NSRange range = NSMakeRange(leng-1, 1);
        requestStr = [requestStr stringByReplacingCharactersInRange:range withString:@""];
        CDLog(@"处理后requstStr=%@",requestStr);
        return requestStr;
    }
}




+(NSString *)getDitie:(NSString *)str{
    NSArray *array = [str componentsSeparatedByString:@";"];
    NSString *strTemp = @"";
    NSString *strReturn = @"";
    for (int i = 0; i<[array count]; i++) {
        strTemp = array[i];
        if (![strTemp isEqualToString:@""]) {
            //地铁X号线－5位 地铁XX号线－6位
            if(strTemp.length==5){
            //如果是5位 从2截3位
                 NSRange rang = NSMakeRange(1, 3);
                strTemp = [strTemp substringWithRange:rang];
            }else if(strTemp.length==6){
            //如果是6位 从2截4位
                NSRange rang = NSMakeRange(1, 4);
                strTemp = [strTemp substringWithRange:rang];
            }
            if ([strReturn rangeOfString:strTemp].location == NSNotFound) {
                strReturn = [strReturn stringByAppendingString:strTemp];
            }
        }
    }
    //号铁 替换为空 ，再斩头去尾
    strReturn = [strReturn stringByReplacingOccurrencesOfString:@"号铁" withString:@"/"];
    NSRange rang = NSMakeRange(1, strReturn.length-2);
    strReturn = [strReturn substringWithRange:rang];
    return strReturn;
}

+(NSString *)hideTel:(NSString *)str{
    NSString *content;
    if (![NSString isEmpty:str ]) {
        if ([NSString isMobileNumber:str]) {
            NSRange range = NSMakeRange(3, 4);
            content = [str stringByReplacingCharactersInRange:range withString:@"****"];
        }
        else
        {
            content = str;
        }
    }
  return content;
}

#pragma mark - MD5加密
- (NSString *)md5Str
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

#pragma mark - SHA1加密
- (NSString*) sha1Str
{
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
    {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}
- (CGFloat)getHeightWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
    return [self getSizeWithFont:font constrainedToSize:size].height;
}

- (CGFloat)getWidthWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
    return [self getSizeWithFont:font constrainedToSize:size].width;
}

#pragma mark - 转换拼音
- (NSString *)transformToPinyin
{
    if (self.length <= 0)
    {
        return self;
    }
    NSString *tempString = [self mutableCopy];
    CFStringTransform((CFMutableStringRef)tempString, NULL, kCFStringTransformToLatin, false);
    tempString = (NSMutableString *)[tempString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
    tempString = [tempString stringByReplacingOccurrencesOfString:@" " withString:@""];
    return [tempString uppercaseString];
}

#pragma mark - 通过字体得到最合适的大小
- (CGSize)getSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
    CGSize resultSize = CGSizeZero;
    if (self.length <= 0)
    {
        return resultSize;
    }
    resultSize = [self boundingRectWithSize:size
                                    options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin)
                                 attributes:@{NSFontAttributeName: font}
                                    context:nil].size;
    resultSize = CGSizeMake(MIN(size.width, ceilf(resultSize.width)), MIN(size.height, ceilf(resultSize.height)));
    return resultSize;
}


#pragma mark emotion_monkey
+ (NSDictionary *)emotion_monkey_dict
{
    static NSDictionary *_emotion_monkey_dict;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
                  {
                      _emotion_monkey_dict = @{
                                               //猴子大表情
                                               @"coding_emoji_01": @"哈哈",
                                               @"coding_emoji_02": @"吐",
                                               @"coding_emoji_03": @"压力山大",
                                               @"coding_emoji_04": @"忧伤",
                                               @"coding_emoji_05": @"坏人",
                                               @"coding_emoji_06": @"酷",
                                               @"coding_emoji_07": @"哼",
                                               @"coding_emoji_08": @"你咬我啊",
                                               @"coding_emoji_09": @"内急",
                                               @"coding_emoji_10": @"32个赞",
                                               @"coding_emoji_11": @"加油",
                                               @"coding_emoji_12": @"闭嘴",
                                               @"coding_emoji_13": @"wow",
                                               @"coding_emoji_14": @"泪流成河",
                                               @"coding_emoji_15": @"NO!",
                                               @"coding_emoji_16": @"疑问",
                                               @"coding_emoji_17": @"耶",
                                               @"coding_emoji_18": @"生日快乐",
                                               @"coding_emoji_19": @"求包养",
                                               @"coding_emoji_20": @"吹泡泡",
                                               @"coding_emoji_21": @"睡觉",
                                               @"coding_emoji_22": @"惊讶",
                                               @"coding_emoji_23": @"Hi",
                                               @"coding_emoji_24": @"打发点咯",
                                               @"coding_emoji_25": @"呵呵",
                                               @"coding_emoji_26": @"喷血",
                                               @"coding_emoji_27": @"Bug",
                                               @"coding_emoji_28": @"听音乐",
                                               @"coding_emoji_29": @"垒码",
                                               @"coding_emoji_30": @"我打你哦",
                                               @"coding_emoji_31": @"顶足球",
                                               @"coding_emoji_32": @"放毒气",
                                               @"coding_emoji_33": @"表白",
                                               @"coding_emoji_34": @"抓瓢虫",
                                               @"coding_emoji_35": @"下班",
                                               @"coding_emoji_36": @"冒泡",
                                               @"coding_emoji_38": @"2015",
                                               @"coding_emoji_39": @"拜年",
                                               @"coding_emoji_40": @"发红包",
                                               @"coding_emoji_41": @"放鞭炮",
                                               @"coding_emoji_42": @"求红包",
                                               @"coding_emoji_43": @"新年快乐",
                                               //猴子大表情 Gif
                                               @"coding_emoji_gif_01": @"奔月",
                                               @"coding_emoji_gif_02": @"吃月饼",
                                               @"coding_emoji_gif_03": @"捞月",
                                               @"coding_emoji_gif_04": @"打招呼",
                                               @"coding_emoji_gif_05": @"悠闲",
                                               @"coding_emoji_gif_06": @"赏月",
                                               @"coding_emoji_gif_07": @"中秋快乐",
                                               @"coding_emoji_gif_08": @"爬爬",
                                               };
                  });
    return _emotion_monkey_dict;
}

- (NSString *)emotionMonkeyName
{
    return [NSString emotion_monkey_dict][self];
}

+ (NSString *)sizeDisplayWithByte:(CGFloat)sizeOfByte
{
    NSString *sizeDisplayStr;
    if (sizeOfByte < 1024)
    {
        sizeDisplayStr = [NSString stringWithFormat:@"%.2f bytes", sizeOfByte];
    }
    else
    {
        CGFloat sizeOfKB = sizeOfByte/1024;
        if (sizeOfKB < 1024)
        {
            sizeDisplayStr = [NSString stringWithFormat:@"%.2f KB", sizeOfKB];
        }
        else
        {
            CGFloat sizeOfM = sizeOfKB/1024;
            if (sizeOfM < 1024)
            {
                sizeDisplayStr = [NSString stringWithFormat:@"%.2f M", sizeOfM];
            }
            else
            {
                CGFloat sizeOfG = sizeOfKB/1024;
                sizeDisplayStr = [NSString stringWithFormat:@"%.2f G", sizeOfG];
            }
        }
    }
    return sizeDisplayStr;
}

#pragma mark - 剔除空白区域
- (NSString *)trimWhitespace
{
    NSMutableString *str = [self mutableCopy];
    CFStringTrimWhitespace((__bridge CFMutableStringRef)str);
    return str;
}


#pragma mark - 判断字符串是否为空
- (BOOL)isEmpty
{
    return [[self trimWhitespace] isEqualToString:@""];
}

/**
 *  根据图片链接 去获得图片的宽高比例
 *
 *  @param urlStr 后台返回的图片链接
 *
 *  @return 图片高/宽比例
 */

+(CGFloat)getImageBiliFromStr:(NSString *)urlStr
{
    if ([NSString isEmpty:urlStr]) {
        return 1;
    }
    NSArray *array  = [urlStr componentsSeparatedByString:@"!!"];
    if (array.count!=2) {
        CDLog(@"图片链接里面没传原始宽和高");
        return 3/4.0;
    }
    else
    {
        NSString *str = array[1];
        NSArray *heightArray = [str componentsSeparatedByString:@"x"];
        if (heightArray.count!=2) {
            CDLog(@"图片链接里面传的原始宽和高形式不对");
            return 3/4.0;
        }
        else
        {
            CGFloat width = [heightArray[0] floatValue];
            CGFloat height = [heightArray[1] floatValue];
            return height/width;
        }
    }
}
/**
 *  根据带宽高比例图片链接 获取原图
 *
 *  @param ulrStr <#ulrStr description#>
 *
 *  @return <#return value description#>
 */
+(NSString *)getImageUrlFromStr:(NSString *)urlStr
{
    if ([NSString isEmpty:urlStr]) {
        return @"";
    }
    NSString *imageUrl ;
    NSArray *array  = [urlStr componentsSeparatedByString:@"!!"];
    if (array.count>0) {
        imageUrl = array[0];
        return imageUrl;
    }
    CDLog(@"后台传的图片链接为空");
    return @"";
}
+(NSString *)getFilePath:(NSString *)FileName
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *downloadPath = [documentPath stringByAppendingPathComponent:FileName];//在前面的文件路径后面 加/FileName
    return downloadPath;//得到需要的路径
}

@end
